package ricky.animate
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.geom.Matrix;
	import flash.utils.Dictionary;
	
	import ricky.Interface.IFrameManager;
	import ricky.cache.ModelCache;
	import ricky.cache.ModelWaitQueue;
	import ricky.events.AnimEvent;
	import ricky.loader.Request;
	import ricky.utils.TimeServer;

	/**
	 * 动画播放对像
	 * 动态加载资源
	 * 多场景播放
	 */
	public class AnimSprite extends Animate implements IEventDispatcher 
	{
		
		public function AnimSprite(fmanager:IFrameManager=null,spritName:String="")
		{
			super(fmanager);
			scenes=new Dictionary();
			sceneNames=new Array();
			this._spritName=spritName;
		}
		
		/**
		 * 当前动画的名
		 * 可以用来查找
		 */
		public function get spritName():String
		{
			return _spritName;
		}
		
		public function set spritName(value:String):void
		{
			_spritName = value;
		}

		/**
		 * 加载要播放的资源
		 * @param url:String 当前加载的url(*.da)只能解析
		 * @param priority:int=1 优先级
		 */
		public function loadModel(model:String,priority:int=1):void
		{
			trace("开始加载"+model);
			ModelCache.instance.getModel(model,this.onComplete,priority);
		}
		
		/**
		 * 卸载正在加载的资源
		 */
		public function unload(model:String):void
		{
			ModelCache.instance.unloadRes(model);
		}
		
		/**
		 * 资源加载完成的时候调用
		 * @param o:Object 打包swf 中的资源类
		 * @param key:String下载资源的key
		 */
		public function onComplete(req:Request):void
		{
			req.onComplete=onAddScene;
			ModelWaitQueue.instance.addToWait(req);
		}
		
		protected function onAddScene(req:Request):void
		{
			var arr:Array=req.data;
			for each(var anis:AnimScene in arr)
			{
				this.addScene(anis);
				//				trace("添加"+anis.actionName);
			}
			
			if(!isNaN(_index))
				this.playSceneByIndex(_index);
			
			if(this._willSceneName)
				this.findSimilarScene(_willSceneName);
			
			if(req.onEnd!=null)
				req.onEnd(req);
			
		}
		
		/**
		 * 添加播放场景
		 * @param scence:AnimScene 需要添加的场景资源
		 */
		public function addScene(scence:AnimScene):void
		{
			if(scence && sceneNames.indexOf(scence.actionName)<0)//没有
			{
				sceneNames.push(scence.actionName);//添加场景
				scenes[scence.actionName]=scence;//放入场景字典中;	
			}
		}
		
		/**
		 * 播放场景
		 * @param sceneName:String 需要播放的场景名 如果不存在则播放第一个场景
		 */
		override public function playScene(sceneName:*=null):void
		{
			if(sceneName!=null)
			{
				if(_currentSceneName!=sceneName)			
					_startTime=TimeServer.now()/1000;//开始时间	
					
				this._currentSceneName=sceneName;
				if(_lastSceneName!=_currentSceneName)
					_lastSceneName=_currentSceneName;
				
				if(this.sceneNames.length==0) //如果没有任何场景播放默认场景
				{
					this.currScene=_defaultScene;
					this._willSceneName=sceneName;
				}
				else
				{
					if(scenes[_currentSceneName]) //如果有当前场景
					{
						currScene=scenes[_currentSceneName];
					}
					else //如果当前场景没有 寻找相似场景
					{
						findSimilarScene(_currentSceneName);
						
						if(_lastSceneName!=null && scenes[_lastSceneName])//如果有上个场景
							currScene= scenes[_lastSceneName];
						
					}
				}
			}

			if(!isPlaying)
				super.playScene();
		}
		
		/**
		 * 寻找最相似的场景
		 */
		private function findSimilarScene(scenceName:String):void
		{
			var temArr:Array=scenceName.split("_");
			tmpAct=temArr[0];
			if(temArr.length>1)
				tmpDir=temArr[1];
			var simi:Array=this.sceneNames.filter(filter);
			simi.sort(compareFunction);
			
			if(simi.length>0)
			{
				var tem:String=simi.shift();
				this.currScene=this.scenes[tem];
				_currentSceneName=tem;
			}
			
			tmpAct=null;
			tmpDir=null;
		}
		private var tmpAct:String=null;
		private var tmpDir:String=null;
		private function filter(element:String, index:int, arr:Array):Boolean {
			if(element.indexOf(tmpAct)>=0)
				return true;
			else if(element.indexOf(tmpDir)>=0)
				return true;
			return false;
		}
		private function compareFunction(a:String, b:String):Number
		{
			var a1:String,d1:int,a2:String,d2:int,arr:Array;
			arr=a.split("_");
			a1=arr[0];
			d1=int(arr[1]);
			arr=b.split("_");
			a2=arr[0];
			d2=int(arr[1]);
			if(tmpAct)
			{
				if(a1==tmpAct && a2==tmpAct)//如果相等
				{
					return Math.abs(d1-int(tmpDir))-Math.abs(d2-int(tmpDir));
				}else if(a1==tmpAct)
				{
					return -1;
				}else if(a2==tmpAct)
					return 1;
			}else
			{
				return Math.abs(d1-int(tmpDir))-Math.abs(d2-int(tmpDir));
			}
			return 0;
		}
		
		/**
		 * 按索引播放动画场景
		 * @param i:uint 场景索引
		 */
		public function playSceneByIndex(i:int):void
		{
			if(sceneNames.length==0)
				_index=i;
			else
			{
				if(i>=this.sceneNames.length)
					i=this.sceneNames.length-1;
				if(i>=0)
					_index=i;
				playScene(sceneNames[_index]);
			}
			
		}

		/**
		 * 得到当前场景
		 */
		override public function get currScene():AnimScene
		{
			return _currScene;
		}
		
		public function set currScene(value:AnimScene):void
		{
			_currScene=value;
			if(this._fps>0 && _currScene)
				_currScene.fps=_fps;
		}
			
		/**
		 * 得到当前的场景名
		 */
		public function get currentSceneName():String
		{
			return _currentSceneName;
		}
		
		
		/**
		 * 得到当前场景所有帧
		 */
		public function get totalFrames():uint
		{
			var tl:uint=0;
			var cs:AnimScene=this.currScene;//如果有当前场景
			if(cs)
				tl=cs.totalFrame;
			return tl;
		}
		
		override public  function dispose():void
		{
			super.dispose();
			defaultBitMap=null;
			bitmapData=null;
			_currentSceneName=null;
			if(sceneNames)
				sceneNames.length=0;
			sceneNames=null;
			scenes=null;
			if(this.parent)
				this.parent.removeChild(this);
		}
		
		/**
		 * 性能关键
		 */
		override public function action(ds:Number):void
		{
			var cs:AnimScene=this.currScene;//如果有当前场景
			if(cs)
			{
				dt=ds-_startTime;

				_offX=0;
				_offY=0;
				cs.calcFrame(dt);//caleFrame(ds,cs);//得到当前帧
				_currFrame=cs.currFrame;
				
				
				if(this.lastFrame==_currFrame && cs.totalFrame!=1) //如果是上一贞不变
					return;
				
				_offX=cs.offx;
				_offY=cs.offy;
				super.x=_x+_offX;
				super.y=_y+_offY;
				var bitdata:BitmapData;
				bitdata=cs.getBitMapData(_currFrame);
				if(!bitdata)
					bitdata=defaultBitMap;
				
				this.bitmapData=bitdata;	
				
				super.lastFrame=_currFrame;
				if(_currFrame==(cs.effctFrame-1)) //效果帧
				{
					this.dispatchEvent(new AnimEvent(AnimEvent.Anim_Effect,this));
				}
				
				if(_currFrame==(cs.totalFrame-1))//播放到最后一帧
				{
					_playTimes++;
					this.dispatchEvent(new AnimEvent(AnimEvent.Anim_End,this));
				}
				
			}else
			{
				this.bitmapData=defaultBitMap;		
			}
		
		}
		
		/**
		 * 计算当前应该播放的帧
		 */
		private function caleFrame(ds:Number,anis:AnimScene):int
		{
			var dt:Number=ds-_startTime;
			var t:uint=anis.totalFrame;
			var f:uint;
			
			if(_fps>0)
				f=_fps;
			else
				f=anis.fps;
			
			if (dt < 0)
				return 0;			
			var fst:* = dt * f;
			currentFrame = fst % t;
			return currentFrame;
		}
		
		/**
		 * 得到存放的场景名
		 */
		public function getKey(sceneName:String):String
		{
			return this._spritName+sceneName;
		}
		
		public function get defaultScene():AnimScene
		{
			return _defaultScene;
		}
		
		/**
		 * 默认播放场景
		 */
		public function set defaultScene(value:AnimScene):void
		{
			_defaultScene = value;
		}
		
		/**
		 * 当前场景开始时间
		 */
		public function get startTime():Number
		{
			return _startTime;
		}
		
		override public function set x(value:Number):void
		{
//			super.x=value;//
			_x=value;
			//+this._offX;
		}
		
		override public function set y(value:Number):void
		{
//			super.y=value;//+this._offY
			_y=value;
		}
		
		/**
		 * 原始x没有偏移的坐标
		 */
		public function get X():Number
		{
			return _x;
		}
		
		public function set X(value:Number):void
		{
			super.x=value;
		}
		
		public function set Y(value:Number):void
		{
			super.y=value;
		}
		/**
		 * 原始y没有偏移的坐标
		 */
		public function get Y():Number
		{
			return _y;
		}
		
		/**
		 * 清除相关资源
		 */
		public function clear():void
		{
			scenes=new Dictionary();
			sceneNames.length=0
			_startTime=0;
			_currentSceneName=null;
			_spritName="";
			_willSceneName=null;
			_lastSceneName=null;
		}
		
		public var scenes:Dictionary;//所有场景 key场景名 AnimScene对像
		public var sceneNames:Array;//所有场景名

		private var _spritName:String="";
		private var _currentSceneName:String=null;//当前场景名		
		private var _lastSceneName:String=null;//上个场景名
		private var _willSceneName:String=null;//将要播放的场景
		private var _startTime:Number=0;//开始播放时间

		/**
		 * 自定义fps 覆盖配置文件中的fps
		 */
		public function get fps():int
		{
			return _fps;
		}

		/**
		 * @private
		 */
		public function set fps(value:int):void
		{
			_fps = value;
		}

		/**
		 * 当前的模型
		 */
		public function get model():String
		{
			return _model;
		}

		protected var _offX:Number=0;
		protected var _offY:Number=0;
		private var _x:Number=0;
		private var _y:Number=0;
		private var _fps:int=0;//播放速度
		private var _currFrame:int=0;//当前帧
		private var _model:String;//模型
		private var _defaultScene:AnimScene;//默认场景
		private var _currScene:AnimScene;//当前场景
		private var dt:Number;//帧时间间隔
		public var defaultBitMap:BitmapData;
		
	}
}